<template>
  <div class="app-container">

    <!-- <div v-show="hasRole(['sciAdmin'])">
    <el-card shadow="always" style="margin-top: 20px;">
      <div class="chart-container">
        <el-card shadow="never" style="margin: 20px;width: 40%;">
          <div ref="barChart" style="width: 100%; height: 200px;"></div>
        </el-card>
        <el-card shadow="never" style="margin: 20px;width: 60%;">
          <div class="pie-and-status-wrapper">
            <div ref="pieChart" style="width: 40%; height: 200px;"></div>
            <div class="status-container">
              <div class="status-item">
                <div class="status-label">申请</div>
                <div class="status-count">{{applicationCount}}</div>
              </div>
              <div class="status-item">
                <div class="status-label">受理</div>
                <div class="status-count">{{acceptanceCount}}</div>
              </div>
              <div class="status-item">
                <div class="status-label">授权</div>
                <div class="status-count">{{authorizationCount}}</div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>
    </div> -->

    <el-card shadow="always" style="margin-top: 20px;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-row :gutter="20">
          <!-- 第一列 -->
          <el-col :span="22">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="所属方向" prop="deptId">
                <el-select v-model="queryParams.deptId" placeholder="请选择所属方向" clearable>
                  <el-option
                    v-for="dept in deptList"
                    :key="dept.deptId"
                    :label="dept.deptName"
                    :value="dept.deptId"
                  />
                </el-select>
                </el-form-item>
                <el-form-item label="申请状态" prop="applicationStatus">
                <el-select v-model="queryParams.applicationStatus" placeholder="请选择申请状态" clearable>
                  <el-option
                  v-for="dict in dict.type.sci_soft_app_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  />
                </el-select>
                </el-form-item>
                <el-form-item label="研究院署名" prop="instituteSignature">
                <el-select v-model="queryParams.instituteSignature" placeholder="请选择研究院署名" clearable>
                  <el-option
                  v-for="dict in dict.type.sci_signature"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  />
                </el-select>
                </el-form-item>

                <el-form-item label="统计年度" prop="statisticalYear">
                  <el-input
                    v-model="queryParams.statisticalYear"
                    placeholder="请输入统计年度"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>


              </el-col>
              <el-col :span="24">

                <el-form-item label="软著名称" prop="softwareName">
                <el-input
                  v-model="queryParams.softwareName"
                  placeholder="请输入软著名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
                </el-form-item>



                <el-form-item label="软著流水号" prop="serialNumber">
                <el-input
                  v-model="queryParams.serialNumber"
                  placeholder="请输入软著流水号"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
                </el-form-item>


                <el-form-item label="著作权人" prop="copyrightOwner">
                <el-input
                  v-model="queryParams.copyrightOwner"
                  placeholder="请输入著作权人"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
                </el-form-item>
                <el-form-item label="申请时间">
                <el-date-picker
                  v-model="daterangeApplicationDate"
                  style="width: 208px"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
                </el-form-item>


              </el-col>
              <el-col :span="24">


              </el-col>
            </el-row>
          </el-col>
          <!-- 第二列 -->
          <el-col :span="2">
            <el-row>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-row>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="always" style="margin-top: 20px;">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:copyright:add']"
          >新增</el-button>
        </el-col>


        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:copyright:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="CopyrightList" @selection-change="handleSelectionChange">

        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="统计年度" align="center" prop="statisticalYear">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_year" :value="scope.row.statisticalYear"/>
        </template>
        </el-table-column>
        <el-table-column label="所属方向" width="190" align="center" prop="deptId">
          <template slot-scope="scope">
            {{ getDeptLabel(scope.row.deptId) }}
          </template>
        </el-table-column>
        <el-table-column label="软著名称" align="center" prop="softwareName" />
        <el-table-column label="申请状态" align="center" prop="applicationStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_soft_app_status" :value="scope.row.applicationStatus"/>
        </template>
        </el-table-column>
        <el-table-column label="研究院署名" align="center" prop="instituteSignature">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_signature" :value="scope.row.instituteSignature"/>
        </template>
        </el-table-column>

        <el-table-column label="软著流水号" align="center" prop="serialNumber" />
        <el-table-column label="著作权人" align="center" prop="copyrightOwner" />
        <el-table-column label="申请时间" align="center" prop="applicationDate" width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applicationDate, '{y}-{m}-{d}') }}</span>
        </template>
        </el-table-column>
        <el-table-column label="授权时间" align="center" prop="authorizationDate" width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.authorizationDate, '{y}-{m}-{d}') }}</span>
        </template>
        </el-table-column>
        <el-table-column label="权利取得方式" align="center" prop="rightsAcquisition">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_rights_method" :value="scope.row.rightsAcquisition"/>
        </template>
        </el-table-column>

        <el-table-column label="所属项目" align="center" prop="projectId">
          <template slot-scope="scope">
            {{ getProjectLabel(scope.row.projectId) }}
          </template>
        </el-table-column>



        <el-table-column label="操作"  width="300" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              type="text"
              style="color: #409EFF;"
              @click="handleView(scope.row)"
              v-hasPermi="['system:copyright:query']"
            >查看</el-button>
            <el-button
              type="text"
              style="color: #E6A23C;"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:copyright:edit']"
            >修改</el-button>
            <el-button
              type="text"
              style="color: #67C23A;"
              @click="handleStatusUpdate(scope.row)"
              v-hasPermi="['system:copyright:status']"
            >状态变更</el-button>
            <el-button
              type="text"
              style="color: #F56C6C;"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:copyright:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改科研专利信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-card shadow="always">
        <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="120px">
          <el-divider ><i class="el-icon-collection"></i>  基本信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="软著名称" prop="softwareName">
                <el-input v-model="form.softwareName" placeholder="请输入软著名称" clearable
                  :style="{width: '100%'}"
                   maxlength="100" show-word-limit></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究方向" prop="deptId">
                <el-select v-model="form.deptId" placeholder="请选择所属方向" clearable :style="{width: '100%'}">
                  <el-option
                    v-for="dept in deptList"
                    :key="dept.deptId"
                    :label="dept.deptName"
                    :value="dept.deptId"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="权利取得方式" prop="rightsAcquisition">
                <el-radio-group v-model="form.rightsAcquisition" size="medium">
                  <el-radio
                    v-for="(item, index) in dict.type.sci_rights_method"
                    :key="index"
                    :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="著作权人" prop="copyrightOwner">
                <el-input v-model="form.copyrightOwner" placeholder="请输入著作权人" clearable :style="{width: '100%'}"
                 maxlength="100" show-word-limit>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="申请状态" prop="applicationStatus">
                <el-radio-group v-model="form.applicationStatus" size="medium">
                  <el-radio
                    v-for="(item, index) in dict.type.sci_soft_app_status"
                    :key="index"
                    :label="item.value"
                    :disabled="!isAdding">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="软著流水号" prop="serialNumber">
                <el-input v-model="form.serialNumber" placeholder="请输入软著流水号" clearable
                  :style="{width: '100%'}"
                  maxlength="20" show-word-limit></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请时间" prop="applicationDate">
                <el-date-picker v-model="form.applicationDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :style="{width: '100%'}" placeholder="请输入申请时间" clearable></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider ><i class="el-icon-postcard"></i>  详细信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合作类型" prop="cooperationType">
                <el-radio-group v-model="form.cooperationType" size="medium">
                  <el-radio v-for="(item, index) in dict.type.sci_cooperation_type" :key="index" :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="授权时间" prop="authorizationDate">
                <el-date-picker v-model="form.authorizationDate" format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请输入授权时间" clearable>
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="统计年度" prop="statisticalYear">
                <el-select v-model="form.statisticalYear" placeholder="请输入统计年度" clearable
                  :style="{width: '100%'}">
                  <el-option v-for="(item, index) in statisticalYearOptions" :key="index" :label="item.label"
                    :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究院署名" prop="instituteSignature">
                <el-radio-group v-model="form.instituteSignature" size="medium">
                  <el-radio v-for="(item, index) in dict.type.sci_signature" :key="index" :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="是否代理" prop="isAgency">
                <el-radio-group v-model="form.isAgency" size="medium">
                  <el-radio v-for="(item, index) in dict.type.sys_yes_no" :key="index" :label="item.value"
                    :disabled="item.disabled">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="所属项目" prop="projectId">
                <el-select v-model="form.projectId" placeholder="请选择所属项目" clearable :style="{width: '100%'}">
               <el-option
                  v-for="project in projectList"
                  :key="project.id"
                  :label="project.projectName"
                  :value="project.id"
                />
              </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider v-if="form.isAgency === '是'"><i class="el-icon-user"></i>  代理信息</el-divider>
          <el-row :gutter="20" v-if="form.isAgency === '是'">
            <el-col :span="8">
              <el-form-item label="代理公司" prop="agencyCompany">
                <el-input v-model="form.agencyCompany" placeholder="请输入单行文本" clearable
                  :style="{width: '100%'}"
                  maxlength="50" show-word-limit></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="代理人" prop="agencyPerson">
                <el-input v-model="form.agencyPerson" placeholder="请输入代理人" clearable
                  :style="{width: '100%'}"
                  maxlength="10" show-word-limit></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="联系人手机号" prop="agencyPhone">
                <el-input v-model="form.agencyPhone" placeholder="请输入手机号" :maxlength="11" show-word-limit clearable
                prefix-icon='el-icon-mobile' :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider  v-if="showFileUpload"><i class="el-icon-folder-opened"></i>  附件文档</el-divider>
          <file-upload-table v-if="showFileUpload" v-model="form.fileRows" :show-add="false"  />
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!-- 添加或修改科研专利信息对话框 -->
    <el-dialog :title="statusTitle" :visible.sync="openStatus" width="900px" append-to-body>
      <el-card shadow="always" >
        <el-form ref="formStatus" :model="formStatus" :rules="rules" size="medium" label-width="120px">
          <el-divider ><i class="el-icon-collection"></i>  状态信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="软著名称" prop="softwareName">
                <el-input :disabled="true" v-model="formStatus.softwareName" placeholder="请输入软著名称" clearable
                  :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="软著流水号" prop="serialNumber">
                <el-input :disabled="true" v-model="formStatus.serialNumber" placeholder="请输入软著流水号" clearable
                  :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="申请状态" prop="applicationStatus">
                <el-radio-group v-model="formStatus.applicationStatus" size="medium">
                  <el-radio
                    v-for="(item, index) in dict.type.sci_soft_app_status"
                    :key="index"
                    :label="item.label"
                    :disabled="index < currentIndex">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="变更时间" prop="authorizationDate" >
                <el-date-picker v-model="formStatus.authorizationDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :style="{width: '100%'}" placeholder="请输入变更时间" clearable></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider  ><i class="el-icon-folder-opened"></i>  附件文档</el-divider>
           <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="文件类型" required>
                <el-select  v-model="formStatus.fileRow.fileClassName" disabled placeholder="请选择文件名称" clearable :style="{width: '100%'}">
                  <el-option v-for="(item, optionIndex) in fileClassNameOptions" :key="optionIndex" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="24">
              <el-form-item  label="上传人" :prop="uploader"  >
                <el-input :disabled="true" v-model="formStatus.fileRow.uploader" placeholder="请输入上传人" clearable :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="上传时间" :prop="uploadTime"  >
                <el-input :disabled="true" v-model="formStatus.fileRow.uploadTime" placeholder="请输入上传时间" clearable :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="附件"  required>
                <file-upload v-model="formStatus.fileRow.fileInfo"
                @update:datetime="handleStatusDatetimeUpdate( $event)"/>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="submitStatusForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-drawer
      title="软著信息"
      :visible.sync="drawer"
      size="50%">

      <el-card shadow="always" style="margin-left: 20px;margin-right: 20px;">
        <div slot="header" >
          <span class="card-title">专利进度</span>

        </div>
        <el-timeline>
          <el-timeline-item
            v-for="(activity, index) in activities"
            :key="index"
            :icon="activity.icon"
            :type="activity.type"
            :color="activity.color"
            :size="activity.size"
            placement="top"
            :timestamp="activity.timestamp">
            <el-card>
              <h4>{{ activity.content }}</h4>
              <p>{{ activity.operator }}提交于 {{ activity.operateTime }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </el-card>

      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="基本信息" border  :column="2">
          <el-descriptions-item label="软著名称"  > {{this.formView.softwareName}}</el-descriptions-item>
          <el-descriptions-item label="研究方向">{{ getDeptLabel(formView.deptId) }}</el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <dict-tag :options="dict.type.sci_soft_app_status" :value="formView.applicationStatus"/>
          </el-descriptions-item>
          <el-descriptions-item label="权利取得方式">
            <dict-tag :options="dict.type.sci_rights_method" :value="formView.rightsAcquisition"/>
          </el-descriptions-item>
          <el-descriptions-item label="著作权人">
            {{this.formView.copyrightOwner}}
          </el-descriptions-item>
          <el-descriptions-item label="软著流水号">{{this.formView.serialNumber}}</el-descriptions-item>
          <el-descriptions-item label="申请时间"  > {{this.formView.applicationDate}}</el-descriptions-item>

        </el-descriptions>
      </el-card>
      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="详细信息" border  :column="2">


          <el-descriptions-item label="合作类型">
            <dict-tag :options="dict.type.sci_cooperation_type" :value="formView.cooperationType"/>
          </el-descriptions-item>
          <el-descriptions-item label="授权时间">{{this.formView.authorizationDate}}</el-descriptions-item>
          <el-descriptions-item label="统计年度"  >
            <dict-tag :options="dict.type.sci_year" :value="formView.statisticalYear"/>
          </el-descriptions-item>
          <el-descriptions-item label="研究院署名">
            <dict-tag :options="dict.type.sci_signature" :value="formView.instituteSignature"/>
          </el-descriptions-item>

          <el-descriptions-item label="是否代理"  >
            <dict-tag :options="dict.type.sys_yes_no" :value="formView.isAgency"/>
          </el-descriptions-item>

          <el-descriptions-item label="所属项目">

              {{ getProjectLabel(this.formView.projectId) }}
          </el-descriptions-item>



        </el-descriptions>
      </el-card>
      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="代理信息" border  :column="2">


          <el-descriptions-item label="代理公司"  > {{this.formView.agencyCompany}}</el-descriptions-item>
          <el-descriptions-item label="代理人">{{this.formView.agencyPerson}}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{this.formView.agencyPhone}}</el-descriptions-item>


        </el-descriptions>
      </el-card>


      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="附件文档" :column="1" border>
          <el-descriptions-item v-for="(row, index) in formView.fileRows" :key="'file-' + index" :label="row.fileClassName || '未命名文件'">
            <div>
              <p>
                <template v-if="row.fileInfo && row.fileInfo.length > 0">
                  <div v-for="(file, fileIndex) in row.fileInfo" :key="fileIndex" style="margin-top: 5px;">
                    <el-link
                      type="primary"
                      target="_blank"
                       @click="handleDownload(file)"
                    >
                      {{ file.originalName }}
                    </el-link>

                    <span style="margin-left: 8px; color: #909399; font-size: 12px">
                      ({{ (file.fileSize/1024).toFixed(2) }} KB)
                    </span>
                  </div>
                </template>
                <span v-else style="color: #909399">无附件</span>
              </p>
              <p>上传人: {{ row.uploader }}</p>
              <p>上传时间: {{ row.uploadTime }}</p>

            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </el-drawer>



  </div>
</template>

<script>
import { listCopyright, getCopyright, delCopyright, addCopyright, updateCopyright,updateStatus,getSoftwareCopyrightCountByStatus,getSoftwareCopyrightCountByDept } from "@/api/sci/copyright";
import { listStatus_log} from "@/api/sci/status_log";
import * as echarts from 'echarts';
import { listDept } from '@/api/system/dept';
import { listProjectInfo } from '@/api/sci/projectInfo';
import { downloadMinioFile } from '@/api/common/common';
import FileUploadTable from '@/views/sci/components/FileUploadTable';
import { checkRole } from '@/utils/permission'




export default {
  name: "Copyright",
  dicts: ['sci_year','sys_yes_no','sci_soft_app_status','sci_cooperation_type','sci_signature','sci_rights_method'],
  components: {
    FileUploadTable
  },
  data() {
    return {
      showFileUpload: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科研专利信息表格数据
      CopyrightList: [],
      // 弹出层标题
      title: "",
      statusForm: {

      },
      statusTitle: "",
      // 是否显示弹出层
      open: false,
       // 是否显示弹出层
      openStatus: false,

      drawer: false,

      isAdding: false,
      // 联系电话时间范围
      daterangeApplicationDate: [],
      // 联系电话时间范围
      daterangeAuthorizationDate: [],
      username : this.$store.state.user.nickName,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        softwareName: null,
        applicationStatus: null,
        deptId: null,
        serialNumber: null,
        copyrightOwner: null,
        applicationDate: null,
        authorizationDate: null,
        cooperationType: null,
        statisticalYear: null,
        instituteSignature: null,
      },
      projectList: [],
      deptList: [],

      activities: [],


      statusToFileMapping: {
        '申请': ['软著代理协议'],
        '受理': ['软著代理协议', '受理通知书'],
        '授权': ['软著代理协议', '受理通知书', '电子证书'],
      },

      statusToFileMapping2: {
        '申请': '软著代理协议',
        '受理': '受理通知书',
        '授权': '电子证书',
      },
      currentStatus: '',

      availableStatuses: [],


      // 表单参数
      form: {
        fileRows: [
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }
        ]
      },
      formStatus: {
        fileRow:
          {
            fileClassName: '',
            uploader: '',
            uploadTime:   '',
            fileInfo: []
          }

      },
      formView: {
        fileRows: [] // 初始化为空数组
      },
      // 表单校验
      rules: {
        softwareName: [{
          required: true,
          message: '请输入软著名称',
          trigger: 'blur'
        }],
        deptId: [{
          required: true,
          message: '请输入研究方向',
          trigger: 'change'
        }],

        copyrightOwner: [{
          required: true,
          message: '请输入著作权人',
          trigger: 'blur'
        }],
        applicationStatus: [{
          required: true,
          message: '申请状态不能为空',
          trigger: 'change'
        }],
        serialNumber: [{
          required: true,
          message: '请输入软著流水号',
          trigger: 'blur'
        }],
        applicationDate: [{
          required: true,
          message: '请选择申请时间',
          trigger: 'blur'
        }],
        authorizationDate: [],
        cooperationType: [{
          required: true,
          message: '合作类型不能为空',
          trigger: 'change'
        }],

        statisticalYear: [{
          required: true,
          message: '请输入统计年度',
          trigger: 'change'
        }],
        instituteSignature: [{
          required: true,
          message: '研究院署名不能为空',
          trigger: 'change'
        }],

        isAgency: [{
          required: true,
          message: '是否代理不能为空',
          trigger: 'change'
        }],

        projectId: [],
        agencyCompany: [{
          required: true,
          message: '请输入单行文本',
          trigger: 'blur'
        }],
        agencyPerson: [{
          required: true,
          message: '请输入代理人',
          trigger: 'blur'
        }],
        agencyPhone: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }, {
          pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          message: '手机号格式错误',
          trigger: 'blur'
        }],
        fileRows: {
          fileClassName: [
            { required: true, message: '请选择文件名称', trigger: 'change' }
          ],

          fileInfo: [
            { required: true, message: '请上传附件', trigger: 'change' }
          ],
        },

        // 'fileRow.fileClassName': [{ required: true }],
        // 'fileRow.fileInfo': [{ required: true }]

      },

      statisticalYearOptions: [{
        "label": "2025",
        "value": "2025"
      }, {
        "label": "2024",
        "value": "2024"
      },{
        "label": "2023",
        "value": "2023"
      }, {
        "label": "2022",
        "value": "2022"
      }],
      fileClassNameOptions: [{
          "label": "软著代理协议",
          "value": "软著代理协议"
        }, {
          "label": "受理通知书",
          "value": "受理通知书"
        }, {
          "label": "电子证书",
          "value": "电子证书"
        }
      ],

    };
  },
  created() {
    this.getList();
    this.getProjectList();
    this.getDeptList();
  },
  mounted() {
    // // this.getList();
    // this.initPieChart();
    // this.initBarChart();
  },
  computed: {
    currentIndex() {
      return this.dict.type.sci_soft_app_status.findIndex(
        item => item.value === this.currentStatus
      );
    }
  },
  watch: {

    'form.applicationStatus': function(newStatus) {
      if (newStatus === '授权') {
        this.$set(this.rules, 'authorizationDate', [
          { required: true, message: '请输入授权时间', trigger: 'change' }
        ]);
      } else {
        this.$set(this.rules, 'authorizationDate', []);
      }

      if(newStatus !==null && newStatus !==''){
        this.showFileUpload = true;
      }else{
        this.showFileUpload = false;
      }

      if(this.isAdding){
        if (this.statusToFileMapping[newStatus]) {

          const requiredFiles = this.statusToFileMapping[newStatus];
          this.form.fileRows = this.form.fileRows.filter(row => requiredFiles.includes(row.fileClassName));
          requiredFiles.forEach(fileName => {
            if (!this.form.fileRows.some(row => row.fileClassName === fileName)) {
              this.form.fileRows.push({
                fileClassName: fileName,
                uploader: this.username,
                uploadTime: '',
                fileInfo: []
              });
            }
          });
        } else {
          this.form.fileRows = [
            {
              fileClassName: '',
              uploader: this.username,
              uploadTime: '',
              fileInfo: []
            }
          ];
        }
      }
    },

    'formStatus.applicationStatus': function(newStatus) {
      this.$set(this.rules, 'authorizationDate', [
          { required: true, message: '请输入授权时间', trigger: 'change' }
        ]);
      if (this.statusToFileMapping2[newStatus]) {
        this.formStatus.fileRow.fileClassName = this.statusToFileMapping2[newStatus];
      } else {
        this.formStatus.fileRow.fileClassName = '';
      }
    },
    'form.isAgency': function(newVal) {
      if (newVal !== '是') {
        this.form.agencyCompany = '';
        this.form.agencyPerson = '';
        this.form.agencyPhone = '';
      }
    }
  },
  methods: {
    // 根据角色判断是否显示
    hasRole(requiredRoles) {
      return checkRole(requiredRoles)
    },
    /** 查询科研专利信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeApplicationDate && '' != this.daterangeApplicationDate) {
        this.queryParams.params["beginApplicationDate"] = this.daterangeApplicationDate[0];
        this.queryParams.params["endApplicationDate"] = this.daterangeApplicationDate[1];
      }
      if (null != this.daterangeAuthorizationDate && '' != this.daterangeAuthorizationDate) {
        this.queryParams.params["beginAuthorizationDate"] = this.daterangeAuthorizationDate[0];
        this.queryParams.params["endAuthorizationDate"] = this.daterangeAuthorizationDate[1];
      }
      listCopyright(this.queryParams).then(response => {
        this.CopyrightList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openStatus = false;
      this.reset();
      this.resetStatus();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        softwareName: null,
        applicationStatus: null,
        deptId: null,
        serialNumber: null,
        copyrightOwner: null,
        applicationDate: null,
        authorizationDate: null,
        cooperationType: null,
        statisticalYear: null,
        instituteSignature: null,
        isAgency: null,
        agencyCompany: null,
        agencyPerson: null,
        agencyPhone: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        fileRows: [  // 保持基础结构
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }
        ]
      };
      this.resetForm("form");
    },
    resetStatus() {
      this.formStatus = {
        id: null,
        projectId: null,
        softwareName: null,
        applicationStatus: null,
        deptId: null,
        serialNumber: null,
        copyrightOwner: null,
        applicationDate: null,
        authorizationDate: null,
        cooperationType: null,
        statisticalYear: null,
        instituteSignature: null,
        isAgency: null,
        agencyCompany: null,
        agencyPerson: null,
        agencyPhone: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        fileRow:   // 保持基础结构
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }
      };
	  this.resetForm("formStatus");
    },
    resetView() {
      this.formView = {
         id: null,
        projectId: null,
        softwareName: null,
        applicationStatus: null,
        deptId: null,
        serialNumber: null,
        copyrightOwner: null,
        applicationDate: null,
        authorizationDate: null,
        cooperationType: null,
        statisticalYear: null,
        instituteSignature: null,
        isAgency: null,
        agencyCompany: null,
        agencyPerson: null,
        agencyPhone: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        fileRow:   // 保持基础结构
          {
            fileClassName: '',
            uploader: '',
            uploadTime: '',
            fileInfo: []
          }

      };
	  this.resetForm("formView");
    },
    handleDatetimeUpdate(index, datetime) {
      // Update the corresponding uploadTime field
      this.$set(this.form.fileRows[index], 'uploadTime', datetime);
    },
    handleStatusDatetimeUpdate(datetime) {
      // Update the corresponding uploadTime field
      this.$set(this.formStatus.fileRow, 'uploadTime', datetime);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeApplicationDate = [];
      this.daterangeAuthorizationDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isAdding=true;
      this.availableStatuses=[],
      this.title = "添加软著信息";
      this.form.fileRows[0].uploader = this.username;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCopyright(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.isAdding=false;
        //is.availableStatuses=['申请', '受理', '初审', '公布', '实审', '授权', '维持'],
        this.title = "修改软著信息";
      });
    },
    handleView(row) {
      this.resetView();
      const id = row.id || this.ids
      getCopyright(id).then(response => {

        if (response.data && response.data.fileRows) {
          response.data.fileRows = response.data.fileRows.map(fileRow => {
            try {
              // 如果fileInfo是字符串则转换为数组，否则保持原样
              fileRow.fileInfo = typeof fileRow.fileInfo === 'string'
                ? JSON.parse(fileRow.fileInfo)
                : fileRow.fileInfo;
            } catch (e) {
              console.error('fileInfo解析失败：', e);
              fileRow.fileInfo = [];
            }
            return fileRow;
          });
        }
        this.formView = response.data;

        const query = {
          entityType: 'SciSoftwareCopyright', // Entity type, e.g., 'Copyright'
          entityId: id, // Entity ID, e.g., Copyright ID
          statusField: 'applicationStatus' // Status field to query
        };
        listStatus_log(query).then(logResponse => {
          this.activities = logResponse.rows.map(item => ({
            content: item.newStatus, // Status description from the API response
            timestamp: this.parseTime(item.statusTime, '{y}-{m}-{d}'),
            operator: item.operator, // Operator from the API response
            operateTime: item.operateTime, // Operator from the API response
            icon: 'el-icon-check', // Default icon
            type: 'primary', // Default type
            color: '#0bbd87', // Default color
            size: 'large' // Default size
          }));
        }).catch(error => {
          console.error('获取状态日志失败：', error);
          this.$message.error('无法加载状态日志');
        });

        console.log(this.activities)


        this.drawer = true;
      });
    },

    parseTime(time, format = '{y}-{m}-{d} {h}:{i}:{s}') {
      if (!time) return '';
      let date = new Date(time);
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds()
      };
      return format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        return value.toString().padStart(2, '0');
      });
    },
    handleDownload(file) {
      const fileName = file.url; // 替换为实际的文件名
      downloadMinioFile(fileName);
    },

    handleStatusUpdate(row) {
      this.resetStatus();
      const id = row.id || this.ids
      getCopyright(id).then(response => {
        const data = response.data;
        this.formStatus.id = data.id;
        this.formStatus.softwareName = data.softwareName;
        this.formStatus.applicationStatus = data.applicationStatus;
        this.formStatus.serialNumber = data.serialNumber;

        this.currentStatus= data.applicationStatus


        this.openStatus = true;
        this.statusTitle = "专利状态变更";
        this.formStatus.fileRow.uploader = this.username;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

           // 再校验子组件数据
          const fileRows = this.form.fileRows;

          if (!fileRows || fileRows.length === 0) {
            this.$message.error('请上传文件');
            return;
          }
          for (let i = 0; i < fileRows.length; i++) {
            const row = fileRows[i];
            if (!row.fileClassName || row.fileClassName.trim() === '') {
              this.$message.error(`第 ${i + 1} 行文件类型不能为空`);
              return;
            }

            if (!row.fileInfo || JSON.parse(row.fileInfo).length === 0) {
              this.$message.error(`第 ${i + 1} 行附件不能为空`);
              return;
            }
          }

          // 增加额外的时间关系验证保险
          if (this.form.authorizationDate && this.form.applicationDate &&
              this.form.authorizationDate <= this.form.applicationDate) {
            this.$message.error('授权时间必须晚于申请时间');
            return;
          }
          const trimmedForm = this.trimFormFields(this.form);
          if (this.form.id != null) {
            updateCopyright(trimmedForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCopyright(trimmedForm).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })

          }
        }
      });
    },

    submitStatusForm() {
      this.$refs["formStatus"].validate(valid => {
        if (valid) {
          // 提交前检查文件是否已上传
          const fileInfo = typeof this.formStatus.fileRow.fileInfo === 'string' ? JSON.parse(this.formStatus.fileRow.fileInfo) : this.formStatus.fileRow.fileInfo;
          if (!fileInfo || !Array.isArray(fileInfo) || fileInfo.length === 0) {
            this.$modal.msgError("请先上传附件");
            return;
          }
          if (this.formStatus.id!= null) {
            updateStatus(this.formStatus).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.openStatus = false;
              this.getList();
            });
          }
        }
      })
    },
    trimFormFields(form) {
      const trimmedForm = { ...form };
      for (const key in trimmedForm) {
        if (typeof trimmedForm[key] === 'string') {
          trimmedForm[key] = trimmedForm[key].trim();
        }
      }
      return trimmedForm;
    },
    getProjectLabel(projectId) {
      const project = this.projectList.find(p => p.id === projectId);
      return project ? project.projectName : '';
    },

    getDeptLabel(deptId) {
      const dept = this.deptList.find(d => d.deptId === deptId);
      return dept ? dept.deptName : '';
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const name=row.softwareName;
      this.$modal.confirm('是否确认删除著作权名为"' + name + '"的数据项？').then(function() {
        return delCopyright(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/copyright/export', {
        ...this.queryParams
      }, `Copyright_${new Date().getTime()}.xlsx`)
    },

    getProjectList() {
      listProjectInfo().then(response => {
        this.projectList = response.rows;
      });
    },
    getDeptList() {
      listDept().then(response => {
        this.deptList = response.data.filter(dept => dept.deptId !== 100);      });
    },

    addRow() {

      this.form.fileRows.push({
        fileClassName: '',
        uploader: this.username,
        uploadTime: '',
        fileInfo: [],
      });
    },
    removeRow(index) {
      if (this.form.fileRows.length > 1) {
        this.form.fileRows.splice(index, 1);
      } else {
        this.$message.warning('至少需要保留一行');
      }
    },

    async initPieChart() {
      try {
        const pieChart = echarts.init(this.$refs.pieChart);

        // 调用接口获取专利状态统计
        const response = await getSoftwareCopyrightCountByStatus(); // 假设该接口返回的数据结构为 [{ status: '申请', count: 10 }, ...]
        const data = response.data || [];

        const statusCounts = data.reduce((acc, item) => {
          if (item.status === '申请') acc.applicationCount = item.count;
          if (item.status === '受理') acc.acceptanceCount = item.count;
          if (item.status === '授权') acc.authorizationCount = item.count;
          return acc;
        }, {
          applicationCount: 0,
          acceptanceCount: 0,
          authorizationCount: 0
        });

        // 将结果赋值给 Vue 实例的 data 属性
        this.applicationCount = statusCounts.applicationCount;
        this.acceptanceCount = statusCounts.acceptanceCount;
        this.authorizationCount = statusCounts.authorizationCount;

        // 将原始数据映射为 ECharts 需要的格式：{ value: count, name: status }
        const seriesData = data.map(item => ({
          value: item.count,
          name: item.status
        }));

        const pieOption = {
          title: {
            text: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)' // 更直观显示百分比
          },
          // legend: {
          //   orient: 'vertical',
          //   left: 'left',
          //   top: 'center'
          // },
          series: [
            {
              name: '专利状态',
              type: 'pie',
              radius: ['40%', '70%'],
              center: ['50%', '50%'],
              data: seriesData, // 使用动态数据
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ],
          graphic: {
            type: 'text',
            left: 'center',
            top: 'center',
            style: {
              text: '软著状态分布',
              textAlign: 'center',
              fontSize: 12,
              fontWeight: 'bold'
            }
          }
        };

        pieChart.setOption(pieOption, true);
      } catch (error) {
        console.error('加载饼图失败:', error);
        this.$message.error('无法加载软著状态数据');
      }
    },

    async initBarChart() {
      try {
        const deptMapping = {
        '能源战略与碳中和路径方向': '能源战略',
        '智慧矿山方向': '智慧矿山',
        '新型储能方向': '新型储能',
        '分布式能源方向': '分布式能源',
        '地下清洁能源资源方向': '地清',
        '二氧化碳捕集利用与封存方向': 'CCUS',
        '节能减碳方向': '节能减碳',
        '能源大数据方向': '能源大数据',
        '能源软件平台方向': '能源软件'
      };
        const response = await getSoftwareCopyrightCountByDept();
        const data = response.data;

        // 提取 X 轴（部门名称）并进行映射转换
        const xAxisData = data.map(item => deptMapping[item.dept_name] || item.dept_name);
        const seriesData = data.map(item => item.patent_count);

        const barChart = echarts.init(this.$refs.barChart);
        const barOption = {
          title: {
            text: '九大方向软著数量',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            data: xAxisData,
            axisLabel: {
              fontSize: 8, // 设置字体大小
              color: '#666' // 设置字体颜色
            }
          },
          yAxis: {
            type: 'value',
            minInterval: 1, // 设置最小刻度为1（整数）
          },
          grid: {
            left: '4%',
            right: '4%',
            bottom: '12%',
            containLabel: true
          },
          series: [
            {
              name: '软著数量',
              type: 'bar',
              barWidth: '40%',
              data: seriesData
            }
          ]
        };

        barChart.setOption(barOption, true); // 使用 true 表示合并配置
      } catch (error) {
        console.error('获取软著数量失败:', error);
        this.$message.error('无法加载部门软著数量');
      }
    }
  }
};
</script>


<style scoped>
.chart-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.center-button {
  display: flex;
  justify-content: center;
}

.card-title {
  font-family: SimHei, sans-serif;
  font-weight: bold;
}

.pie-and-status-wrapper {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  width: 100%;
}

.status-container {
  width: 60%;
  height: 200px;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-label {
  color: #909399; /* 浅灰色 */
  font-size: 16px; /* 放大字体 */
  margin-bottom: 8px;
}

.status-count {
  color: #4985fc; /* 浅灰色 */
  font-size: 40px; /* 放大字体 */
  font-weight: bold;
}
.el-table__row .cell {
  text-align: center;
}
</style>
